//
//  BKCMBuyCarVC.m
//  bestkeep
//
//  Created by 毛韶谦 on 2017/1/16.
//  Copyright © 2017年 utouu. All rights reserved.
//

#import "BKCMBuyCarVC.h"
#import "BKSCCommon.h"
#import "Mediator+BKMy.h"
#import "BKCMBuyCarMainCell.h"
#import "BKCMGetDataFromNetwork.h"
#import "BKCMFooterView.h"
#import "BKCMBuyCarSectionView.h"
#import "BKCMBuyCarMainCell.h"
#import "BKCMRecommendCell.h"
#import "Mediator+BKOrder.h"
#import "Mediator+BKGD.h"
#import "ExceptionView.h"

#define BUYCARRECOMMENDHEIGHT (IPHONE_WIDTH - 24.0f)/2.0f/345.0f*428.0f+8.0f

@interface BKCMBuyCarVC ()<UITableViewDataSource,UITableViewDelegate,cellButtonDetegate,FooterAccountViewDelegate,BuyCarSectionDelegate>

@property (nonatomic, strong) BKCMBuyCarSectionView* buyCarSectionView;  //每一组的头部
@property (nonatomic, strong) BKCMFooterView *footerAccountView;   //结算
@property (nonatomic, strong) BKSCBuyCarTool *buyCarTools;  //购物车的工具类
@property (nonatomic, strong) ExceptionView *exceptionView;
@property (nonatomic, strong) UITableView *buyCarTableView;
@property (nonatomic, strong) UIScrollView *headScrollView; //TableView的headView；
/**   商品详情的bool   */
@property (nonatomic, strong) NSMutableDictionary *mutableSelectedDictionary;  //记录被选中的所有cell；
@property (nonatomic, strong) NSMutableArray *dataSource; // 接受购物车数据数组
@property (nonatomic, strong) NSMutableArray *sectionHeaderViewArray; // tableview的headview数组
@property (nonatomic, strong) NSMutableArray *goodID_array; // 记录商品ID
@property (nonatomic, strong) NSMutableArray *selected_OrderArray; // 选择的商品数组
@property (nonatomic, strong) NSMutableArray *recommendGoodsList;//推荐数组
@property (nonatomic, strong) NSMutableArray *deleteCarGoodsArray;  //暂时存储要删除的商品的数组；
@property (nonatomic, strong) NSString *currentPage; //推荐当前页数；
@property (nonatomic, strong) NSString *totalPage;  //推荐页面 一共几页

@end

@implementation BKCMBuyCarVC

{
    NSMutableArray *global_Array; // 全球购状态数组
    NSDictionary *userDictionary;  //存放用户信息的字典
    UIButton  *leftButton;  // 右侧按钮
    NSString *thnormaltype;
    BOOL isAllShopsLose;   //是否所以得商品全部失效；
    BOOL isOdd;  //判断推荐商品数是否是奇数；
    BOOL isLeftScreen;  //判断点击是否在屏幕左侧；
    BOOL isReloadData;  //是否重复加载；
    BOOL isWillAppearView;  //防止每次进入都有加载圈；
    BOOL isLogin;  //记录是否是登录状态
    BOOL isCollectGoods; //是否是收藏商品；
}

#pragma  mark -------------懒加载，防止多次创建--------------------

- (UIScrollView *)headScrollView {
    
    if (!_headScrollView) {
        if (iPhone4 || iPhone5) {
            _headScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, IPHONE_WIDTH, 460/2)];
            _headScrollView.bounces = NO;
            _headScrollView.scrollEnabled = NO;
            _headScrollView.contentSize = CGSizeMake(IPHONE_WIDTH, 460/2);
        }else {
            
            _headScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, IPHONE_WIDTH, 536/2)];
            _headScrollView.bounces = NO;
            _headScrollView.contentSize = CGSizeMake(IPHONE_WIDTH, 536/2);
        }
        _headScrollView.backgroundColor = BUYCARGRAYCOLOR;
        [self.view addSubview:_headScrollView];
    }
    return _headScrollView;
}

- (NSMutableArray *)deleteCarGoodsArray {
    
    if (!_deleteCarGoodsArray) {
        _deleteCarGoodsArray = [NSMutableArray array];
    }
    return _deleteCarGoodsArray;
}

- (UITableView *)buyCarTableView {
    
    if (!_buyCarTableView) {
        
        _buyCarTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT-44.0f) style:UITableViewStyleGrouped];
        _buyCarTableView.allowsSelection = YES;
        [_buyCarTableView setBackgroundColor:BUYCARGRAYCOLOR];//RGB(242, 242, 242)
        _buyCarTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_buyCarTableView];
        [self afreshLayoutTableView];
    }
    return _buyCarTableView;
}

- (NSMutableArray *)recommendGoodsList {
    
    if (!_recommendGoodsList) {
        _recommendGoodsList = [NSMutableArray array];
    }
    return _recommendGoodsList;
}

- (BKCMFooterView *)footerAccountView {
    
    if (!_footerAccountView) {
        
        _footerAccountView = [[BKCMFooterView alloc] init];
        _footerAccountView.footerDelegate = self;
        [self.view addSubview:_footerAccountView];
        [_footerAccountView setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self afreshLayoutTableView];
    }
    return _footerAccountView;
}
- (NSMutableArray *)dataSource {
    
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc] init];
    }
    return _dataSource;
}
- (NSMutableArray *)sectionHeaderViewArray {
    
    if (!_sectionHeaderViewArray) {
        _sectionHeaderViewArray = [NSMutableArray array];
    }
    return _sectionHeaderViewArray;
}
- (NSMutableDictionary *)mutableSelectedDictionary {
    
    if (!_mutableSelectedDictionary) {
        _mutableSelectedDictionary = [[NSMutableDictionary alloc] init];
    }
    return _mutableSelectedDictionary;
}
- (NSMutableArray *)goodID_array {
    
    if (!_goodID_array) {
        _goodID_array = [NSMutableArray array];
    }
    return _goodID_array;
}

#pragma mark --------------视图生命周期-----------------------

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self dataInitializeWhenViewLoad];//初始化相关数据
    [self setCancelButton]; // 设置右侧button
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self loadBuyCarCell];
}

- (void)dataInitializeWhenViewLoad {
    
    isWillAppearView = YES;
    self.currentPage = [NSString stringWithFormat:@"1"];
    self.title = BKSCLocalizedString(@"BKSCControllerTitle");
    self.view.backgroundColor = BUYCARGRAYCOLOR;
    [self setupRefresh]; // 设置刷新
    //用于传值调用；
    _buyCarTools = [[BKSCBuyCarTool alloc] init];
}

- (void) loadBuyCarCell {
    
    userDictionary = [[Mediator sharedInstance]BKMyUserInfo];
    isLogin = [userDictionary[@"BKMyUserIsLoginKey"] boolValue];
    
    [self shoopCartList_again];//数据加载
}

//界面的重新布局
- (void)afreshLayoutTableView {
    
    [_buyCarTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
        make.top.mas_equalTo(self.view.mas_top);
        if (self.dataSource.count == 0 || !isLogin) {
            make.bottom.mas_equalTo(self.view.mas_bottom);
        }else {
            if (self.tabBarController.tabBar.isHidden) {
                make.bottom.mas_equalTo(self.footerAccountView.mas_top);
            }else {
                make.bottom.mas_equalTo(self.footerAccountView.mas_top).offset(49.0f);
            }
        }
    }];
    
    [_footerAccountView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
        if ( self.tabBarController.tabBar.isHidden) {
            make.bottom.mas_equalTo(self.view.mas_bottom);
        }else {
            make.bottom.mas_equalTo(self.view.mas_bottom).mas_offset(-49.0f);
        }
        make.height.mas_equalTo(@(50));
    }];
    
}

// 刷新数据
-(void)update{
    
    [self updatePromptView];
    [self shoopCartList_again];
}
-(void)updatePromptView {
    
    
    if (_headScrollView && (self.buyCarTableView.contentOffset.y  < self.headScrollView.frame.size.height - 64)) {
        [self.buyCarTableView setContentOffset:CGPointMake(0, -64) animated:YES];
    }
    for (UIView *subView in self.view.subviews) {
        if (subView.tag == 17776 || subView.tag == 17777 || subView.tag == 17778) {
            [subView removeFromSuperview];
        }
    }
    [self.headScrollView removeFromSuperview];//TableView的headView；
    self.headScrollView = nil;
    //对tableHeaderView进行清除失败，不得已；
    self.buyCarTableView.tableHeaderView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, FLT_MIN)];
}

#pragma mark - -----请求相关--------
/**
 *  每次来到购物车模块，再次请求数据，判断刷新
 */
-(void)shoopCartList_again{
    
    if (isWillAppearView) {
        [LoadingView loadingShoppingCartInView:self.view];
        isWillAppearView = NO;
    }
    if (self.exceptionView) {
        [self.exceptionView dismiss];
        self.exceptionView = nil;
    }
    if (!isLogin) {
        
        [self.dataSource removeAllObjects];
        [self.sectionHeaderViewArray removeAllObjects];
        [self.goodID_array removeAllObjects];
        [self presentLoginViewController];
        return;
    }
    __weak typeof(self)wSelf = self;
    [BKCMGetDataFromNetwork GetBuycarDataFromJsonSuccess:^(NSArray *bkModels) {
        
        [self.dataSource removeAllObjects];
        [self.sectionHeaderViewArray removeAllObjects];
        [self.goodID_array removeAllObjects];
        [self.dataSource addObjectsFromArray:bkModels];
        for ( BKCMRecommendGoodsModel *super_SH in   self.dataSource) {
            NSMutableArray * marr=[NSMutableArray arrayWithArray:super_SH.shopList];
            for ( BKCMGoodsDetailModel* shoppingCarList in marr) {
                
                [self.goodID_array addObject:shoppingCarList.record_id];
            }
        }
        if ([[NSString stringWithFormat:@"%zd",self.goodID_array.count] integerValue] > 0) {// 更新购物车角标
            [BKSCBuyCarTool updataBageIntage:[[NSString stringWithFormat:@"%zd",self.goodID_array.count] integerValue] bottomView:wSelf.tabBarController.tabBar];
            leftButton.hidden = NO;
        }else{
            [BKSCBuyCarTool updataBageIntage:0 bottomView:wSelf.tabBarController.tabBar];
            leftButton.hidden = YES;
        }
        
        self.buyCarTableView.hidden = NO;
        /****************       购物车数量为零     ****************/
        if (self.dataSource.count == 0) {
            
            [self updatePromptView];//清除提示View；
            
            //更新recommendTableView frame；
            [self afreshLayoutTableView];
            leftButton.hidden = YES;
            self.footerAccountView.hidden = YES;
            self.headScrollView.frame = CGRectMake(0, 64, IPHONE_WIDTH, IPHONE_WIDTH*644.0f/750.0f);
            [_buyCarTools showEmptyMsgViewTo:self.headScrollView emptyText:@"您的购物车还是空的哦" buttonTitle:@"去购物"];
            self.buyCarTableView.tableHeaderView = self.headScrollView;
            
            //block回调 执行方法
            [_buyCarTools setRetryBlock:^(UIButton *sender){
                    isWillAppearView = YES;
                    if (!wSelf.tabBarController.tabBar.isHidden) {
                        
                        wSelf.tabBarController.selectedIndex = 0;
                    }else{
                        [wSelf.navigationController popViewControllerAnimated:YES];
                    }
            }];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                [self.mutableSelectedDictionary removeAllObjects];
                [BKSCBuyCarTool writeBuyCarSelectDictionary:self.mutableSelectedDictionary];
            });
            [self.buyCarTableView reloadData];
            //刷新结束，计算价格
            [self setButtonTitle:self.footerAccountView.accountLable withPriceLabel:self.footerAccountView.label3];
            [self getShopingCarRecommendListFromNet];
            
        }else{
            [self updatePromptView];//清除提示View；
            [self afreshLayoutTableView];//更新recommendTableView frame；
            /****************       购物车数量不为零     ****************/
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                
                NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]initWithDictionary:[BKSCBuyCarTool readBuyCarSelectDictionaryWithFilePath]];
                if (dictionary.count) {
                    self.mutableSelectedDictionary = dictionary;
                }
            });
            
            if ([self.navigationItem.title  isEqual: BKSCLocalizedString(@"BKSCControllerRecommendTitle")]) {
                self.navigationItem.title = BKSCLocalizedString(@"BKSCControllerTitle");
            }
            
            int i = 0;
            for ( BKCMRecommendGoodsModel *super_SH in self.dataSource) {
                for ( BKCMGoodsDetailModel* shoppingCarList in super_SH.shopList) {
                    i++;
                    if (!shoppingCarList.shopcart_flag) {
                        [self.mutableSelectedDictionary removeObjectForKey:shoppingCarList.record_id];
                    }
                }
            }
            
            self.footerAccountView.hidden = NO;
            leftButton.hidden = NO;
            
            for (NSString *good_local in [self.mutableSelectedDictionary allKeys]) {
                BOOL isNotExit = NO;
                for (NSString *record_id in self.goodID_array) {
                    
                    if ([good_local isEqualToString:record_id]) {
                        isNotExit = YES;
                    }
                }
                
                if (!isNotExit) {
                    [self.mutableSelectedDictionary removeObjectForKey:good_local];
                }
            }
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                [BKSCBuyCarTool writeBuyCarSelectDictionary:self.mutableSelectedDictionary];
            });
            
            //防止两次数据请求的时间差
            if ([self.currentPage integerValue]==[self.totalPage integerValue]) {
                self.buyCarTableView.tableFooterView = [self initializationRecommendFooterView];
                [self.buyCarTableView.mj_footer setHidden:YES];
            }
            [self.buyCarTableView reloadData];
            //刷新结束，计算价格
            [self setButtonTitle:self.footerAccountView.accountLable withPriceLabel:self.footerAccountView.label3];
            [LoadingView dismiss];
            [self getShopingCarRecommendListFromNet];
        }
    } failure:^(NSString *error) {
        
        [self updatePromptView];
        self.footerAccountView.hidden = YES;
        self.buyCarTableView.hidden = YES;
        [BKSCBuyCarTool updataBageIntage:0 bottomView:wSelf.tabBarController.tabBar];
        //网络判断
        [self justRequestReachabilityStatusError:error isRecommendListFromNet:NO];
        [LoadingView dismiss];
    }];
    
}


- (void)getShopingCarRecommendListFromNet {
    
    [BKCMGetDataFromNetwork GetBuycarRecommendGoodsDataFromJsonSucessWithParamer:self.currentPage Success:^(id obj) {
        
        BKCMRecommendGoodsModel *super_SH = obj;
        self.totalPage = super_SH.totalPage;
        self.currentPage = super_SH.currentPage;
        if ([self.currentPage integerValue] == 1) {
            [self.recommendGoodsList removeAllObjects];
            isReloadData = NO;
        }
        if (!isReloadData) {
            for (BKCMGoodsDetailModel *shpo in super_SH.shopList) {
                [self.recommendGoodsList addObject:shpo];
            }
            isReloadData = YES;
        }
        if (self.recommendGoodsList.count%2 == 1) {
            isOdd = YES;
        }else {
            isOdd = NO;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if ([self.currentPage integerValue]==[self.totalPage integerValue] ) {
                self.buyCarTableView.tableFooterView = [self initializationRecommendFooterView];
                [self.buyCarTableView.mj_footer setHidden:YES];
            }else {
                [self.buyCarTableView.mj_footer setHidden:NO];
                [self.buyCarTableView.tableFooterView removeFromSuperview];
                self.buyCarTableView.tableFooterView = nil;
            }
            self.buyCarTableView.hidden = NO;
            [self.buyCarTableView.mj_footer endRefreshing];
            [self.buyCarTableView.mj_header endRefreshing];
            [self.buyCarTableView reloadData];
            //刷新结束，计算价格
            [self setButtonTitle:self.footerAccountView.accountLable withPriceLabel:self.footerAccountView.label3];
            [LoadingView dismiss];
        });
    } failure:^(NSString *error) {
        
        [self.buyCarTableView.mj_footer endRefreshing];
        [self.buyCarTableView.mj_header endRefreshing];
        if (!isReloadData && [self.currentPage integerValue] != 1) {
            self.currentPage = [NSString stringWithFormat:@"%ld",(long)([self.currentPage integerValue]-1)];
        }
        [self justRequestReachabilityStatusError:error isRecommendListFromNet:YES];
        [LoadingView dismiss];
    }];
}

- (void)justRequestReachabilityStatusError:(NSString *)error isRecommendListFromNet:(BOOL)isRecommen{
    
    if (!isLogin || !isRecommen) {
        RequestReachabilityStatus status = [RequestManager reachabilityStatus];
        
        if (status == RequestReachabilityStatusNotReachable) {
            
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
        }else if ([error isEqualToString:@"-1009"]) {
            
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
        }else if ([error isEqualToString:@"-1001"]) {
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeRequestFailed];
        }else if ([error isEqualToString:@"502"] || ([error isEqualToString:@"404"])) {
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeServerError];
        }else {
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeFailedToLoad];
        }

        ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:ExceptionCodeTypeServerError handler:^(ExceptionViewAction *action) {
            isWillAppearView = YES;
            [self shoopCartList_again];
        }];
        [self.exceptionView addAction:retryAction];
        [self.exceptionView showInView:self.view];
    }
}

#pragma mark------修改购物车商品相关请求--------------

/* 1、删除购物车商品  - deleteToSaveWuthOrderArr: andShowMessage:
 2、移购物车商品到收藏夹 - moveToSaveWithOrderAr
 */
//修改订单
-(void)changeOrderWithArray:(NSArray *)orderArr{
    NSMutableArray * dictArr = [[NSMutableArray alloc] init];
    [orderArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        BKCMGoodsDetailModel * shopCarModel = (BKCMGoodsDetailModel *)obj;
        NSMutableDictionary * tempDict = [[NSMutableDictionary alloc] init];
        [tempDict setObject:shopCarModel.record_id forKey:@"id"];
        [tempDict setObject:shopCarModel.amount forKey:@"amount"];
        [dictArr addObject:tempDict];
    }];
    
    NSString * paramsStr = [BKSCCommon arrayToJson:dictArr];
    
    [BKCMGetDataFromNetwork editBuyCarGoodsFromJson:paramsStr success:^(id obj) {
        
    } failure:^(NSError *error) {
        
    }];
}

-(void)deleteToSaveWuthOrderArr:(NSArray *)orderArr {
    NSMutableArray * orderArray = [[NSMutableArray alloc] init];
    for (BKCMGoodsDetailModel * model in orderArr) {
        [orderArray addObject:model.record_id];
    }
    if (orderArray.count > 0) {
        NSString * orderStr = [orderArray componentsJoinedByString:@","];
        NSLog(@"/删除购物车商品/%@",orderStr);
        __weak typeof(self)wSelf = self;
        [HUD showProgress:nil inView:self.view];
        [BKCMGetDataFromNetwork deleteBuyCarGoods:orderStr success:^(id obj) {
            
            NSDictionary *dic = obj;
            NSArray * seleectedOrderArr = [wSelf getSelectedOrder];
            for (BKCMGoodsDetailModel * shopCarModel in seleectedOrderArr) {
                
                for (NSString *record_id in [self.mutableSelectedDictionary allKeys]) {
                    if ([shopCarModel.record_id isEqualToString:record_id]) {
                        [wSelf.mutableSelectedDictionary removeObjectForKey:record_id];
                    }
                }
            }
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                [BKSCBuyCarTool writeBuyCarSelectDictionary:self.mutableSelectedDictionary];
                
            });

            [wSelf update];
            [HUD dismissInView:self.view];
            if (!isCollectGoods) {
                BKAnimatedAlert *animatedAlert = [[BKAnimatedAlert alloc] init];
                [animatedAlert BKAlert_Style:BKAlertStyle_Success detail:dic[@"msg"]];
            }
            isCollectGoods = NO;
           
        } failure:^(NSError *error) {
            [HUD dismissInView:self.view];
            isCollectGoods = NO;
            [wSelf update];
        }];
    }
}

-(void)moveToSaveWithOrderArr:(NSArray *)orderArr{
    NSMutableArray * orderArray = [[NSMutableArray alloc] init];
    for (BKCMGoodsDetailModel * model in orderArr) {
        [orderArray addObject:model.good_id];
    }
    if (orderArray.count > 0) {
        NSString * orderStr = [orderArray componentsJoinedByString:@","];
        __weak typeof(self)wSelf = self;
        
        [BKCMGetDataFromNetwork moveToSaveBuyCarGoods:orderStr success:^(id obj) {
            NSDictionary *dic = obj;
            isCollectGoods = YES;
            [wSelf deleteToSaveWuthOrderArr:orderArr];
            BKAnimatedAlert *animatedAlert = [[BKAnimatedAlert alloc] init];
            [animatedAlert BKAlert_Style:BKAlertStyle_Success detail:dic[@"msg"]];
        } failure:^(NSError *error) {
            
        }];
    }
}

#pragma mark - ----------创建控件相关--------------

-(void)createHeaderView{
    
    [self.sectionHeaderViewArray removeAllObjects];
    for (int i = 0; i<self.dataSource.count; i++) {
        BKCMBuyCarSectionView * sectionView =[[BKCMBuyCarSectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 50)];
        sectionView.sectionImageView.hidden = YES;
        sectionView.sectionDelegate = self;
        [self.sectionHeaderViewArray addObject:sectionView];
    }
}

-(void)setCancelButton{
    leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 35, 45);
    leftButton.tag = 470;
    [leftButton setTitle:BKSCLocalizedString(@"BKSCRightButtonEditor") forState:UIControlStateNormal];
    [leftButton setTitle:BKSCLocalizedString(@"BKSCRightButtonComplete") forState:UIControlStateSelected];
    leftButton.titleLabel.font=[UIFont systemFontOfSize:14];
    leftButton.titleLabel.textAlignment = NSTextAlignmentRight;
    [leftButton setTitleColor:HexColor(0x888888) forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    [leftButton addTarget:self action:@selector(editAction:) forControlEvents:UIControlEventTouchUpInside];
    leftButton.hidden = YES;
}
/**
 *  创建尾视图，显示没有更多
 *
 *  @return 尾视图的UIView
 */
- (UIView *)initializationRecommendFooterView {
    
    if ([self.currentPage integerValue] == [self.totalPage integerValue] && self.currentPage) {
        
        return [BKSCBuyCarTool getViewWhenDataEndLoading];
    }
    return nil;
}

-(void)editAction:(UIButton *)testButton{
    
    testButton.selected = !testButton.selected;
    
    [self setAllEditStatus:testButton.selected];
    [self.footerAccountView updateFooterAccountView:[self isHaveEditStatu]];
    [self.buyCarTableView reloadData];
    //刷新结束，计算价格
    [self setButtonTitle:self.footerAccountView.accountLable withPriceLabel:self.footerAccountView.label3];
}

-(void)setAllEditStatus:(BOOL)isEdit{
    for (int i = 0; i<self.dataSource.count; i++) {
        [self setAllEditStatuWithSection:i edit:isEdit];
    }
}
/**
 *  刷新设置；
 */
-(void)setupRefresh{
    
    self.buyCarTableView.delegate = self;
    self.buyCarTableView.dataSource = self;
    
    MJRefreshGifHeader *header = [BKRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(shoopCartList_again)];
    self.buyCarTableView.mj_header = header;
    
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        if ([self.currentPage integerValue]<[self.totalPage integerValue]) {
            self.currentPage = [NSString stringWithFormat:@"%ld",(long)([self.currentPage integerValue]+1)];
            isReloadData = NO;
            [self getShopingCarRecommendListFromNet];
            
        }else {
            [self.buyCarTableView.mj_footer endRefreshing];
        }
    }];
    footer.stateLabel.textColor = LoadMoreDataTitleColor;
    footer.stateLabel.font = [UIFont systemFontOfSize:14];
    footer.arrowView.image = [UIImage imageNamed:@"BKGDPullDown"];
    UIActivityIndicatorView *loadingView = [footer valueForKeyPath:@"loadingView"];
    loadingView.hidesWhenStopped = YES;
    loadingView.color=IndictorViewColor;
    [footer addSubview:loadingView];
    self.buyCarTableView.mj_footer.automaticallyHidden = YES;
    [self.buyCarTableView.mj_footer setHidden:YES];
    self.buyCarTableView.mj_footer = footer;
}

#pragma mark - ----------------TableViewDelegate 代理方法--------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    /**
     *  reloadData 只需走一次的方法。
     */
    if (!self.sectionHeaderViewArray.count) {
        
        [self createHeaderView];
    }
    
    isAllShopsLose = [BKSCBuyCarTool getAllShopLoss:self.dataSource];
    
    if (self.recommendGoodsList.count>0) {
        return self.dataSource.count + 1;
    }
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (section == self.dataSource.count) {
        NSInteger recommendListCount = 0;
        recommendListCount = self.recommendGoodsList.count/2;
        if (isOdd) {
            recommendListCount += 1;
        }
        return recommendListCount;
    }
    
    BKCMRecommendGoodsModel* shopList1 = [self.dataSource objectAtIndex:section];
    return shopList1.shopList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    if (section == self.dataSource.count) {
        return 40;
    }else {
        if (section == 0) {
            return 38;
        }
        return 32.0f;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == self.dataSource.count-1) {
        
        return 20;
    }
    return FLT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.dataSource.count == indexPath.section) {
        return BUYCARRECOMMENDHEIGHT;
    }
    
    BKCMRecommendGoodsModel *superShopping = [self.dataSource objectAtIndex:indexPath.section];
    BKCMGoodsDetailModel* cellList = superShopping.shopList[indexPath.row];
    if ([self.mutableSelectedDictionary allKeys].count) {
        for (NSString *record_id in [self.mutableSelectedDictionary allKeys]) {
            if ([record_id isEqualToString:cellList.record_id]) {
                cellList.isCellBtnSelect = YES;
            }
        }
    }
    return 136 ;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    if (self.dataSource.count == section ) {
        return [BKSCBuyCarTool initializationRecommendFirstSectionView];
    }
    BKCMBuyCarSectionView * sectionView = [self.sectionHeaderViewArray objectAtIndex:section];
    
     return [sectionView sectionView:self.dataSource viewForHeaderInSection:section sectionView:sectionView leftButton:leftButton selectDic:self.mutableSelectedDictionary];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [self.footerAccountView updateAllSelectedButtonSelected:[self getAllSelectedStatus]];
    if (indexPath.section == self.dataSource.count) {
        
        BKCMRecommendCell *recommendCell = [tableView dequeueReusableCellWithIdentifier:@"recommendCell"];
        if (!recommendCell) {
            recommendCell = [[BKCMRecommendCell  alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"recommendCell"];
        }
        
        [recommendCell dealRecommendTabelViewCell:recommendCell recommendGoodsList:self.recommendGoodsList indexPath:indexPath isOdd:isOdd];
        
        return recommendCell;
    }
    
    BKCMRecommendGoodsModel* shopList1 = [self.dataSource objectAtIndex:indexPath.section];
    
    BKCMGoodsDetailModel* cellList = shopList1.shopList[indexPath.row];
    
    NSString *BuyCarllID = [NSString stringWithFormat:@"NoReuseCell_RecordId%@_UserName%@_GoodsPrice%@_GoodsTax%@_GoodsAmount%@_GoodsAmount%@sendDate_param%@",cellList.record_id,userDictionary[@"BKMyUserInfoGetUserIdKey"],cellList.goods_price,cellList.tax_amount,cellList.goods_share_amount,cellList.amount,cellList.sendDate_param];
    BKCMBuyCarMainCell *buyCarDetailCell = [tableView dequeueReusableCellWithIdentifier:BuyCarllID];
    
    if (!buyCarDetailCell) {
        buyCarDetailCell = [[BKCMBuyCarMainCell  alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:BuyCarllID];
        buyCarDetailCell.selectionStyle = UITableViewCellSelectionStyleNone;
        buyCarDetailCell.cellBtnDetegate = self;
    }
    
    if (shopList1) {
        
        [buyCarDetailCell dealBuyCarDetailCell:buyCarDetailCell superShopping:shopList1 leftButton:leftButton indexPath:indexPath];
    }
    
    return buyCarDetailCell;
}


- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    void(^rowActionHandler)(UITableViewRowAction *, NSIndexPath *) = ^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [self setEditing:true animated:true];
        //用于判断点击
        NSString *delegetStr = @"删除";
        NSString *recommentStr = @"收藏";
        if (IOS_VERSION < 8.0) {
            delegetStr = @"删除W";
            recommentStr = @"收藏W";
        }
        
        BKCMRecommendGoodsModel* shopList1 = [self.dataSource objectAtIndex:indexPath.section];
        BKCMGoodsDetailModel* cellList = shopList1.shopList[indexPath.row];
        if ([action.title isEqualToString:delegetStr]) {
            
            [self.deleteCarGoodsArray removeAllObjects];
            [self.deleteCarGoodsArray addObject:cellList];
            [self deleteToSaveWuthOrderArr:self.deleteCarGoodsArray];
            
        }else if ([action.title isEqualToString:recommentStr]) {
            
            [self moveToSaveWithOrderArr:@[cellList]];
        }
        if (shopList1.shopList.count == 1) {
            
            [shopList1.shopList removeObjectAtIndex:indexPath.row];
            [self.dataSource removeObjectAtIndex:indexPath.section];
            [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
        }else {
            [shopList1.shopList removeObjectAtIndex:indexPath.row];
            [self.buyCarTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }

    };
    
    
    if (indexPath.section == self.dataSource.count) {
        return @[];
    }
    NSString *delegetStr = @"删除";
    NSString *recommentStr = @"收藏";
    if (IOS_VERSION < 8.0) {
        delegetStr = @"删除W";
        recommentStr = @"收藏W";
    }
    UITableViewRowAction *deleteRoWAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:delegetStr handler:rowActionHandler];//此处是iOS8.0以后苹果最新推出的api，UITableViewRowAction，Style是划出的标签颜色等状态的定义，这里也可自行定义
    
    UITableViewRowAction *editRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:recommentStr handler:rowActionHandler];
    editRowAction.backgroundColor = COLOR_05;//可以定义RowAction的颜色
    return @[deleteRoWAction, editRowAction];//最后返回这俩个RowAction 的数组
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    if (indexPath.section == self.dataSource.count) {
        
    }else {
        [self setEditing:true animated:true];
    }
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section != self.dataSource.count) {
        
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleDelete;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == self.dataSource.count) {
        return NO;
    }
    return YES;
}

/**
 跳转到商品详情页动画的方法
 
 @param frame 当前商品的frame
 @param goodsId 商品id
 @param saleTypes 营销参数
 @param goodsCoverImg 商品图片
 */
-(void)goodsDetailAnimationWithFrame:(CGRect)frame goodsId:(NSString*)goodsId saleTypes:(id)saleTypes goodsCoverImg:(NSString*)goodsCoverImg{
    
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:frame];
    imageview.image = [CacheImage imageFromKey:goodsCoverImg];
    imageview.contentMode = UIViewContentModeScaleAspectFill;
    imageview.userInteractionEnabled = YES;
    UIView *maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, ScreenHeight)];
    maskView.backgroundColor = [UIColor whiteColor];
    [maskView addSubview:imageview];
    [[UIApplication sharedApplication].keyWindow addSubview:maskView];
    
    [UIView animateWithDuration:0.3 animations:^{
        imageview.frame = CGRectMake(0, 0, SCREENWIDTH, SCREENWIDTH);
    } completion:^(BOOL finished) {
        if (maskView) {
            [maskView removeFromSuperview];
        }
        UIViewController *goodistVC = [[Mediator sharedInstance] BKGD_goodsDetailViewController:goodsId saleTypes:saleTypes goodsCoverImg:goodsCoverImg];
        [self.navigationController pushViewController:goodistVC animated:NO];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{// ---------跳转商品详情页面----------
    
    if (indexPath.section == self.dataSource.count) {
        
        CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];
        CGRect rect = [tableView convertRect:rectInTableView toView:[tableView superview]];
        
        if (isLeftScreen) {//左侧商品
            BKCMGoodsDetailModel *model = [self.recommendGoodsList objectAtIndex:indexPath.row*2];
            
            if (model.good_id) {
                
                CGRect frame = CGRectMake(ApplicationBackGauge, rect.origin.y+10, 70, 70);
                
                [self goodsDetailAnimationWithFrame:frame goodsId:model.good_id saleTypes:@"" goodsCoverImg:model.goods_img];
            }
            
        }else {
            
            if (isOdd && self.recommendGoodsList.count/2 == indexPath.row) {
                return;
            }
            BKCMGoodsDetailModel *model = [self.recommendGoodsList objectAtIndex:indexPath.row*2+1];
            if (model.good_id) {
                
                CGRect frame = CGRectMake(ScreenWidth/2+ApplicationBackGauge, rect.origin.y+10, 70, 70);
                
                [self goodsDetailAnimationWithFrame:frame goodsId:model.good_id saleTypes:@"" goodsCoverImg:model.goods_img];
            }
        }
    }else {
        
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        BKCMRecommendGoodsModel* shopList1 = [self.dataSource objectAtIndex:indexPath.section];
        BKCMGoodsDetailModel* cellList = shopList1.shopList[indexPath.row];
        
        CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];
        CGRect rect = [tableView convertRect:rectInTableView toView:[tableView superview]];
        
        if (cellList.good_id) {
            
            CGRect frame = CGRectMake(25+ApplicationBackGauge, rect.origin.y+15, 100, 100);
            
            [self goodsDetailAnimationWithFrame:frame goodsId:cellList.good_id saleTypes:@"" goodsCoverImg:cellList.goods_img];
        }
    }
}
/**
 *  滑动时调用
 *
 *  @param scrollView 本界面时tableView；
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (![self.navigationController.viewControllers.lastObject isEqual:self]) {
        return;
    }
    if ((scrollView.contentOffset.y > -64.f && (self.dataSource.count == 0 || !isLogin))) {
        
        CGPoint point = scrollView.contentOffset;
        point.y = - point.y/1.5 - 64.f/1.5;
        self.headScrollView.contentOffset = point;
        CGFloat contentFloat = self.headScrollView.frame.size.height-20;
        
        if (scrollView.contentOffset.y > contentFloat) {
            self.navigationItem.title = BKSCLocalizedString(@"BKSCControllerRecommendTitle");
        }else {
            self.navigationItem.title = BKSCLocalizedString(@"BKSCControllerTitle");
        }
    }
}


#pragma mark  - ---------------touch Cancle Keyboard触控监测---------------------------

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{//-------点击事件取消键盘并且恢复原始数据-------
    
    [_buyCarTableView endEditing:YES];
    UITouch *touch = [touches anyObject];   //视图中的所有对象
    CGPoint point = [touch locationInView:self.view]; //返回触摸点在视图中的当前坐标
    int x = point.x;
    if (x > self.view.frame.size.width/2) {
        isLeftScreen = NO;
    }else {
        isLeftScreen = YES;
    }
}

#pragma mark - ----------------cell代理---------------------
//cell左侧的选择状态按钮方法；
- (void)updataCellButtonModel:(BKCMGoodsDetailModel*)sender tableViewCell:(BKCMBuyCarMainCell *)cell
{
    
    for (NSString *record_id in [self.mutableSelectedDictionary allKeys]) {
        if ([sender.record_id isEqualToString:record_id]) {
            if (!sender.isCellBtnSelect) {
                [self.mutableSelectedDictionary removeObjectForKey:record_id];
            }
        }
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [BKSCBuyCarTool writeBuyCarSelectDictionary:self.mutableSelectedDictionary];
        
    });
    [_buyCarTableView reloadData];
    //刷新结束，计算价格
    [self setButtonTitle:self.footerAccountView.accountLable withPriceLabel:self.footerAccountView.label3];
}
//改变商品数量时调用；
-(void)updataCellContentData:(BKCMGoodsDetailModel *)shoppingCarList tableViewCell:(BKCMBuyCarMainCell *)cell{

    [self changeOrderWithArray:@[shoppingCarList]];
    [self.buyCarTableView reloadData];
    //刷新结束，计算价格
    [self setButtonTitle:self.footerAccountView.accountLable withPriceLabel:self.footerAccountView.label3];
}

#pragma mark - -----------------model的编辑或者选中状态--------------------------
-(void)setAllEditStatuWithSection:(NSInteger)section edit:(BOOL)edited{
    if (self.dataSource.count) {
        BKCMRecommendGoodsModel * sectionArray = [self.dataSource objectAtIndex:section];
        if (sectionArray.shopList.count) {
            for (BKCMGoodsDetailModel * shopCarModel in sectionArray.shopList) {
                shopCarModel.isEdit = edited;
            }
        }
    }
}

-(void)setAllSelectedStatuWithSection:(NSInteger)section selected:(BOOL)selected{
    
    if (self.dataSource.count) {
        BKCMRecommendGoodsModel * sectionArray = [self.dataSource objectAtIndex:section];
        if (sectionArray.shopList.count) {
            
            [self.mutableSelectedDictionary removeAllObjects];
            for (BKCMGoodsDetailModel * shopCarModel in sectionArray.shopList) {
                
                if (!shopCarModel.shopcart_flag && !leftButton.selected) {  //商品失效，跳出；
                    shopCarModel.isCellBtnSelect = NO;
                    continue;
                }else if (!shopCarModel.shopcart_flag) {
                    shopCarModel.isCellBtnSelect = selected;
                    
                }else {
                    shopCarModel.isCellBtnSelect = selected;
                }
                for (NSString *record_id in [self.mutableSelectedDictionary allKeys]) {
                    if ([shopCarModel.record_id isEqualToString:record_id]) {
                        if (shopCarModel.isCellBtnSelect) {
                            
                            [self.mutableSelectedDictionary setObject:record_id forKey:record_id];
                        }
                    }
                }
            }
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                
                [BKSCBuyCarTool writeBuyCarSelectDictionary:self.mutableSelectedDictionary];
                
            });
        }
    }
}

#pragma mark - section 代理
//这里面需要做的有改变是否编辑的状态 判断是否有订单被修改 修改订单
-(void)sectionView:(BKCMBuyCarSectionView *)sectionView editButtonClick:(UIButton *)editButton{
    
    [self setAllEditStatuWithSection:sectionView.index edit:editButton.selected];
    if ([self getAllSelectedEditStatus]) {
        leftButton.selected = YES;
    }else{
        leftButton.selected = NO;
    }
    [self.buyCarTableView reloadData];
    //刷新结束，计算价格
    [self setButtonTitle:self.footerAccountView.accountLable withPriceLabel:self.footerAccountView.label3];
    [self.footerAccountView updateFooterAccountView:[self isHaveEditStatu]];
}
-(void)sectionView:(BKCMBuyCarSectionView *)sectionView sectionButtonClick:(UIButton *)sectionButton{
    [self setAllSelectedStatuWithSection:sectionView.index selected:sectionButton.selected];
    [self.buyCarTableView reloadData];
    //刷新结束，计算价格
    [self setButtonTitle:self.footerAccountView.accountLable withPriceLabel:self.footerAccountView.label3];
}

-(void)setButtonTitle:(UILabel *)sectionButton withPriceLabel:(UILabel*)priceLabel{
    NSArray * seletedOrderArr = [self getSelectedOrder];
    
    long signAoumat = 0;
    for (BKCMGoodsDetailModel * tempModel in seletedOrderArr) {
        signAoumat += [[NSString stringWithFormat:@"%@",tempModel.amount] longLongValue];
    }
    if (signAoumat > 99) {
        sectionButton.text = @"99+";
    }else {
        sectionButton.text = [NSString stringWithFormat:@"%ld",signAoumat];
    }
    float i = 0.0;
    for (BKCMGoodsDetailModel * tempModel in seletedOrderArr) {
        float amount = [[NSString stringWithFormat:@"%@",tempModel.amount] doubleValue];
        i += [NSString stringWithFormat:@"%@",tempModel.member_price].doubleValue * amount;
    }
    [priceLabel setText:[NSString stringWithFormat:@"￥%.2f",i]];
    [self.footerAccountView setFooterAmountValue];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - sectionbutton 状态
-(BOOL)getAllSelectedStatus{
    for (int i = 0; i<self.dataSource.count; i++) {
        if (![BKSCBuyCarTool getSectionSelectedStatu:[self.dataSource objectAtIndex:i]mutableSelectedDictionary:self.mutableSelectedDictionary leftButton:leftButton]) {
            return NO;
        }
    }
    //当所有的商品都已失效
    if (isAllShopsLose && !leftButton.selected) { //全已失效进入；
        return NO;
    }
    return YES;
}

-(BOOL)getAllSelectedEditStatus{
    for (int i = 0; i<self.dataSource.count; i++) {
        if (![self getSectionEditBtnSelectedStatu:[self.dataSource objectAtIndex:i]]) {
            return NO;
        }
    }
    return YES;
}
-(BOOL)getSectionEditBtnSelectedStatu:(BKCMRecommendGoodsModel *)section{
    if (section.shopList.count) {
        for (BKCMGoodsDetailModel * model in section.shopList) {
            if (!model.isEdit) {
                return NO;
            }
        }
        return YES;
    }
    return NO;
}

-(BOOL)getAllEditSatus{
    for (int i = 0; i<self.dataSource.count; i++) {
        if (![self getEditSatus:[self.dataSource objectAtIndex:i]]) {
            return NO;
        }
    }
    return YES;
}

-(BOOL)getEditSatus:(BKCMRecommendGoodsModel *)section{
    if (section.shopList.count) {
        for (BKCMGoodsDetailModel * shopIngModel in section.shopList) {
            
            if (shopIngModel.isEdit) {
                return YES;
            }
        }
        return NO;
    }
    return NO;
}
-(BOOL)isHaveEditStatu{
    for (int i = 0; i<self.dataSource.count; i++) {
        if([self getEditSatus:[self.dataSource objectAtIndex:i]]){
            return YES;
        }
    }
    return NO;
}

-(NSMutableArray *)getSelectedOrder{
    
    return [BKSCBuyCarTool getSelectedOrderArray:self.dataSource mutableSelectedDictionary:self.mutableSelectedDictionary leftButton:leftButton];
}

#pragma mark - footer 代理
-(void)setAllSelectedWithAllSelected:(BOOL)allSelected{
    __weak typeof(self)wSelf = self;
    
    [self.dataSource enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [wSelf setAllSelectedStatuWithSection:idx selected:allSelected];
    }];
}
-(void)footerAccountView:(BKCMFooterView *)footerAccountView allSelectedButtonClicked:(UIButton *)allselectedButton{
    
    
    BOOL isAllshopsLose = NO;
    for (BKCMRecommendGoodsModel *superShopModel in self.dataSource) {
        if (!superShopModel.isShopcart_flag) {//全部失效为YES；
            isAllshopsLose = YES;
        }
    }
    if (!isAllshopsLose && !leftButton.selected) {
        
        BKAnimatedAlert *animatedAlert = [[BKAnimatedAlert alloc] init];
        [animatedAlert BKAlert_Style:BKAlertStyle_Waring detail:@"全已失效！"];
    }else {
        [self setAllSelectedWithAllSelected:allselectedButton.selected];
    }
    
    [self.buyCarTableView reloadData];
    //刷新结束，计算价格
    [self setButtonTitle:self.footerAccountView.accountLable withPriceLabel:self.footerAccountView.label3];
}
-(void)footerAccountView:(BKCMFooterView *)footerAccountView moveToSaveButtonClicked:(UIButton *)moveToSaveButton{
    NSArray * seleectedOrderArr = [self getSelectedOrder];
    for (BKCMGoodsDetailModel * shopCarModel in seleectedOrderArr) {
        
        for (NSString *record_id in [self.mutableSelectedDictionary allKeys]) {
            if ([shopCarModel.record_id isEqualToString:record_id]) {
                [self.mutableSelectedDictionary removeObjectForKey:record_id];
            }
        }
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [BKSCBuyCarTool writeBuyCarSelectDictionary:self.mutableSelectedDictionary];
        
    });
    if (seleectedOrderArr.count>0) {
        [self moveToSaveWithOrderArr:[self getSelectedOrder]];
    }else{
        
        [self showAlertMessage:@"请选择商品"];
    }
}
-(void)footerAccountView:(BKCMFooterView *)footerAccountView deleteButtonClicked:(UIButton *)deleteButton{
    NSArray * seleectedOrderArr = [self getSelectedOrder];
    [self.deleteCarGoodsArray removeAllObjects];  //清除原有
    for (BKCMGoodsDetailModel * shopCarModel in seleectedOrderArr) {
        [self.deleteCarGoodsArray addObject:shopCarModel];
    }
    if (seleectedOrderArr.count>0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"确认将这%lu个商品删除吗？",(unsigned long)seleectedOrderArr.count] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alertView.tag = 1991;
        [alertView show];
    }else{
        [self showAlertMessage:@"请选择商品"];
    }
}
#pragma mark  去结算
-(void)footerAccountView:(BKCMFooterView *)footerAccountView calculateButtonClicked:(UIButton *)calculateButton{
    
    NSMutableArray * selectedOrder = [self getSelectedOrder];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [BKSCBuyCarTool writeBuyCarSelectDictionary:self.mutableSelectedDictionary];
        
    });
    NSMutableArray *goodsinfo_array = [NSMutableArray new];
    global_Array = [NSMutableArray new];
    if (selectedOrder.count != 0) {
        for (BKCMGoodsDetailModel *SC in selectedOrder) {
            NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
            [dic1 setObject:SC.good_id forKey:@"goods_id"];
            [dic1 setObject:SC.amount forKey:@"amount"];
            [dic1 setObject:SC.member_price forKey:@"menber_price"];
            [dic1 setObject:SC.goods_reserve_id forKey:@"goods_reserve_id"];
            if (SC.sendDate_param) {
                [dic1 setObject:SC.sendDate_param forKey:@"sendDate"];
            }else{
                [dic1 setObject:@"" forKey:@"sendDate"];
            }
            if (SC.thNormalType) {
                [dic1 setObject:@"1" forKey:@"thnormaltype"];
                thnormaltype = @"1";
            }else {
                [dic1 setObject:@"0" forKey:@"thnormaltype"];
                thnormaltype = @"0";
            }
            if (SC.storeId) {
                [dic1 setObject:SC.storeId forKey:@"storeId"];
            }
            if (SC.shopKeeper) {
                [dic1 setObject:SC.shopKeeper forKey:@"shopKeeper"];
            }
            
            [dic1 setObject:SC.userPrice forKey:@"userPrice"];
            [dic1 setObject:[NSString stringWithFormat:@"%d",SC.buyEarth] forKey:@"global_status"];
            [global_Array addObject:[NSString stringWithFormat:@"%d",SC.buyEarth]];
            [goodsinfo_array addObject:dic1];
        }
        [self preConfirmWithArray:goodsinfo_array];
    }
    else{
        [self showAlertMessage:@"请选择商品"];
    }
}
//结算矫正
- (void)preConfirmWithArray:(NSMutableArray *)sc_array {
    
    NSMutableDictionary *param_dic = [NSMutableDictionary dictionary];
    [param_dic setObject:sc_array forKey:@"goods_info"];
    [param_dic setObject:@"" forKey:@"deliver_id"];
    [param_dic setObject:@"-1" forKey:@"usedShoppingTicketId"];
    [param_dic setObject:@"" forKey:@"integralGoodsId"];
    
    NSString *jsonstr = [BKSCCommon dictionaryToJson:param_dic];
    [HUD showProgress:nil inView:self.view];
    [BKCMGetDataFromNetwork SettlementCheckBuyCarGoods:jsonstr returnInformation:^(id obj) {
        
        [HUD dismissInView:self.view];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:sc_array,@"orderInfo", nil];
        UIViewController *orderVC = [[Mediator sharedInstance] BKOrder_orderViewControllerWithParameter:dic];
        [self.navigationController pushViewController:orderVC animated:YES];
        
    } failure:^(NSError *error) {
        
        [HUD dismissInView:self.view];
    }];    
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark -----------UIAlertViewDelegate-------------
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
            NSLog(@"---------点击了取消----------");
            break;
            
        case 1:
            NSLog(@"========确定删除商品==========");
            if (alertView.tag == 1991) {  //多任务操作是，调用；
                [self.footerAccountView updateFooterAccountView:NO]; // 更新footerAccountView状态
                leftButton.selected = NO; // 更新右侧按钮状态
                if (self.goodID_array.count - self.deleteCarGoodsArray.count > 0) {// 删除是判断是否隐藏_footerAccountView
                }else{
                    self.footerAccountView.hidden = YES;
                }
                [self deleteToSaveWuthOrderArr:self.deleteCarGoodsArray];
            }else {
                [self deleteToSaveWuthOrderArr:self.deleteCarGoodsArray];
            }
            
            break;
            
        default:
            break;
    }
}

#pragma mark - ============方法添加=============

- (void)presentLoginViewController {
    
    self.footerAccountView.hidden = YES;
    [self.buyCarTableView reloadData];
    leftButton.hidden = YES;
    //清除掉头部提示View
    [self updatePromptView];
    //确定加载第一页数据；
    self.currentPage = @"1";
    //重新布局
    [self afreshLayoutTableView];
    
    [_buyCarTools showEmptyMsgViewTo:self.headScrollView
                                                emptyText:@"您还未登录哦，赶快去登录吧!"
                                              buttonTitle:@"立即登录"];
    
    self.buyCarTableView.tableHeaderView = self.headScrollView;
    
    __weak typeof(self)wSelf = self;
    [_buyCarTools setRetryBlock:^(UIButton *sender){
        
            [[Mediator sharedInstance] userGoToLoginFromOrignalController:wSelf finishBlock:^{
                
            }];
            
            isWillAppearView = YES;
    }];
    //加载推荐数据；
    [self getShopingCarRecommendListFromNet];
}

- (void)showAlertMessage:(NSString *)message {
    
    BKAnimatedAlert *animatedAlert = [[BKAnimatedAlert alloc] init];
    [animatedAlert BKAlert_Style:BKAlertStyle_Waring detail:message];
}



-(void)getScAmount:(void(^)(NSString *str))block{
    
    NSDictionary *dic = [[Mediator sharedInstance]BKMyUserInfo];
    isLogin = [dic[@"BKMyUserIsLoginKey"] boolValue];
    //   没有登录
    if (!isLogin){
        block(@"0");
        return;
    }
    [BKCMGetDataFromNetwork GetBuyCarAmountSuccess:^(id obj) {
        
        NSString *amount = (NSString *)obj;
        block(amount);
    } ErrorMessage:^(id obj) {
        
    } failure:^(NSError *error) {
        
    }];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
